package com.example.service;

import com.example.GDModel.AroundSearchInfoResData;
import com.example.GDModel.AroundSearchResData;
import com.example.GDModel.BaseResData;
import com.example.GDModel.DeleteResData;
import com.example.Util.GDUtil;
import com.example.VO.*;
import com.example.mapper.ReportMapper;
import com.example.mapper.RequestMapper;
import com.example.mapper.UserMapper;
import com.example.model.*;
import com.fasterxml.jackson.databind.deser.Deserializers;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ykbboom on 2017/3/3.
 */
@Service("requestService")
public class RequestService {
    private Logger logger = Logger.getLogger(RequestService.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RequestMapper requestMapper;
    @Autowired
    private ReportMapper reportMapper;
    private String[]latlong;
    private String[]startAndStop;

    /**
     * 发布请求
     * */
    @Transactional
    public Integer publishRequest(String userPhone,UserRequest userRequest){
        BaseResData baseResDataStart = GDUtil.CreateSingleData(userPhone,userRequest.getPlace()+","+userRequest.getDestination()
                ,GDUtil.swapLatLong(userRequest.getLatlongStart()), GDInfo.GD_MAP_TABLE_ID_START);
        BaseResData baseResDataDes = GDUtil.CreateSingleData(userPhone,userRequest.getPlace()+","+userRequest.getDestination()
                ,GDUtil.swapLatLong(userRequest.getLatlongDes()), GDInfo.GD_MAP_TABLE_ID_STOP);
        if (baseResDataStart.status==1&&baseResDataDes.status==1){
            userRequest.setGdIdStart(baseResDataStart._id);
            userRequest.setGdIdStop(baseResDataDes._id);
            Integer i = requestMapper.publishRequest(userRequest);
            if (i!=null){
                return new Integer(1);
            }else {
                logger.info("发布请求失败");
                return null;
            }
        }else {
            logger.info("高德请求失败无法创建数据");
            return null;
        }
    }
    /**
     * 获取请求详细信息
     * */
    @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
    public UserRequestDetailVO getRequestDetail(int gdIdStart){
        UserRequest userRequest = requestMapper.getUserRequestDetailByGdId(gdIdStart);
        if (userRequest==null){
            UserRequestDetailVO userRequestDetailVO = new UserRequestDetailVO();
            userRequestDetailVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            userRequestDetailVO.setMsg("服务器未知异常");
            return userRequestDetailVO;
        }else {
            String msg;
            if (userRequest.getAccept()==0){
                msg = "未完成";
            }else {
                msg = "正在进行中...";
            }
            UserRequestDetailVO userRequestDetailVO = new UserRequestDetailVO(
                    userRequest.getRequestId(),userRequest.getPicurl(),userRequest.getDescription(),
                    userRequest.getPlace(),userRequest.getDestination(),userRequest.getTime(),
                    msg,userRequest.getUserId(),userRequest.getGdIdStart(),userRequest.getGdIdStop()
            ,userMapper.getUserNameByUserId(userRequest.getUserId()),userMapper.getUserPhoneByUserId(userRequest.getUserId()));
            userRequestDetailVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
            return userRequestDetailVO;
        }
    }
    /**
     * 云图检索
     * */
    public AroundSearchVO aroundSearch(String userPhone,String center, String radius){
        AroundSearchResData aroundSearchResData = GDUtil.AroundSearch(userPhone,center,radius, GDInfo.GD_MAP_TABLE_ID_START);
        AroundSearchVO aroundSearchVO = new AroundSearchVO();
        if (aroundSearchResData.status==1&&aroundSearchResData.info.equals("OK")){
            List<AroundSearchInfoVO>aroundSearchInfoVOS = new ArrayList<>();

            if (aroundSearchResData.datas!=null&&aroundSearchResData.datas.size()!=0){
                for (AroundSearchInfoResData aroundSearchInfoResData:aroundSearchResData.datas){
                    latlong = aroundSearchInfoResData.get_location().split(",");
                    startAndStop = aroundSearchInfoResData.get_name().split(",");
                    AroundSearchInfoVO aroundSearchInfoVO = new AroundSearchInfoVO(
                            Double.parseDouble(latlong[1]),//纬度
                            Double.parseDouble(latlong[0]),//经度
                            aroundSearchInfoResData.get_distance(),
                            startAndStop[0],//起点
                            startAndStop[1],//终点
                            aroundSearchInfoResData.get_id());
                    aroundSearchInfoVOS.add(aroundSearchInfoVO);

                }
                aroundSearchVO.setAroundSearchInfoVOS(aroundSearchInfoVOS);
                aroundSearchVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
                aroundSearchVO.setMsg("检索周围请求成功");
                return aroundSearchVO;
            }else {
                aroundSearchVO.setAroundSearchInfoVOS(aroundSearchInfoVOS);
                aroundSearchVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
                aroundSearchVO.setMsg("未检索到数据,请扩大检索范围(设置)");
                return aroundSearchVO;
            }

        }else {
            aroundSearchVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            aroundSearchVO.setMsg("服务端未知异常");
            return aroundSearchVO;
        }

    }
    /**
     * 获取个人所有请求
     * */
    @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
    public UserAllRequestVO getUserAllRequest(String userPhone,Integer count){
        int userId = userMapper.getUserIdByUserPhone(userPhone);
        int reqCount = requestMapper.getUserRequestCount(userId);
        UserAllRequestVO userAllRequestVO = new UserAllRequestVO();
        if (reqCount==count){
            logger.info("安卓端缓存用户发布请求数"+count);
            userAllRequestVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            userAllRequestVO.setMsg("未检索到新数据");
            return userAllRequestVO;
        }
        List<UserRequest> list = requestMapper.getUserAllRequest(userId);
        if (list!=null&&list.size()!=0){
            List<MyUserRequestItemVO>mList = new ArrayList<>();
            for (UserRequest userRequest:list){
                StringBuilder s = new StringBuilder();
                if (userRequest.getAccept()==0){
                    s.append("未接受");
                }else if (userRequest.getAccept()==1&&userRequest.getComplete()==0){
                    s.append("正在进行中...");
                }else if (userRequest.getAccept()==1&&userRequest.getComplete()==1){
                    s.append("已完成");
                }
                if(userRequest.getAccept()==1){//请求已被接受
                    int requestId = userRequest.getRequestId();
                    int driverId = requestMapper.getDriverIdByRequestId(requestId);
                    DriverInfo driverInfo = userMapper.getDriverInfo(driverId);
                    MyUserRequestItemVO myUserRequestItemVO = new MyUserRequestItemVO(
                            userRequest.getRequestId(),userRequest.getPicurl(),
                            userRequest.getPlace(),userRequest.getDestination(),
                            userRequest.getTime(),s.toString(),userRequest.getDescription(),driverInfo.getDriverName(),driverInfo.getDriverPhone());
                    mList.add(myUserRequestItemVO);
                }else {
                    MyUserRequestItemVO myUserRequestItemVO = new MyUserRequestItemVO(
                            userRequest.getRequestId(),userRequest.getPicurl(),
                            userRequest.getPlace(),userRequest.getDestination(),
                            userRequest.getTime(),s.toString(),userRequest.getDescription(),"暂无信息","暂无信息");
                    mList.add(myUserRequestItemVO);
                }
            }
            userAllRequestVO.setList(mList);
            userAllRequestVO.setCount(reqCount);
            userAllRequestVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
            userAllRequestVO.setMsg("刷新成功");
            return userAllRequestVO;
        }else {
            userAllRequestVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            userAllRequestVO.setMsg("未检索到新数据");
            return userAllRequestVO;
        }

    }
    /**
     * 删除请求
     * */
    @Transactional
    public BaseResultVO deleteUserRequest(int requestId){
        NetGDId netGDId = requestMapper.getGDId(requestId);
        Integer accept = requestMapper.checkRequestAccepted(requestId);
        Integer reqRes = requestMapper.deleteUserRequest(requestId);
        BaseResultVO baseResultVO = new BaseResultVO();
        if (accept!=0){
            Integer orderRes = requestMapper.deleteUserOrder(requestId);
            logger.info("车主接单已删除");
        }
        if (reqRes!=null){
            DeleteResData resData = GDUtil.DeleteData(String.valueOf(netGDId.getStartId()), GDInfo.GD_MAP_TABLE_ID_START);
            DeleteResData resData1 = GDUtil.DeleteData(String.valueOf(netGDId.getStopId()), GDInfo.GD_MAP_TABLE_ID_STOP);
            if (resData.status==1&&resData.info.equals("OK")&&resData1.status==1&&resData1.info.equals("OK")){
                baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
                baseResultVO.setMsg("删除成功");
                return baseResultVO;
            }else {
                baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
                baseResultVO.setMsg("Error云图端删除错误");
                return baseResultVO;
            }
        }else {
            baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            baseResultVO.setMsg("服务器异常");
            return baseResultVO;
        }
    }
    /**
     * 接受请求
     * */
    @Transactional
    public BaseResultVO acceptRequest(String userPhone,int gdIdStart){
        BaseResultVO baseResultVO = new BaseResultVO();
        int requestId = requestMapper.getRequestIdByGdIdStart(gdIdStart);
        int userId = userMapper.getUserIdByUserPhone(userPhone);
        requestMapper.updateUserAccept(requestId);
        Integer i = requestMapper.acceptRequest(new UserOrder(requestId,userId));
        if (i!=null){
            //云图端更新请求标志为已被接单
            BaseResData baseResData = GDUtil.UpdateData(String.valueOf(gdIdStart),GDInfo.GD_MAP_TABLE_ID_START);
            if (baseResData.status==1&&baseResData.info.equals("OK")){
                baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
                baseResultVO.setMsg("成功接单");
                return baseResultVO;
            }else {
                baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
                baseResultVO.setMsg("未知异常，无法接单");
                return baseResultVO;
            }
        }else {
            baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            baseResultVO.setMsg("云图端无法更新，暂不能接单");
            return baseResultVO;
        }

    }
    /**
     * 获取个人所有接单
     * */
    @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
    public UserAllOrderVO getUserAllOrder(String userPhone,int orderCount){
        int driverId = userMapper.getUserIdByUserPhone(userPhone);
        int count = requestMapper.getUserOrderCount(driverId);
        UserAllOrderVO userAllOrderVO = new UserAllOrderVO();
        if (count==orderCount){
            logger.info("安卓端缓存用户接单数"+orderCount);
            userAllOrderVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            userAllOrderVO.setMsg("没有新的接单");
            return userAllOrderVO;
        }
        List<Integer> list = requestMapper.getDriverAllOrder(driverId);//获取到所有订单Id
        if (list!=null&&list.size()!=0){
            List<OrderItemVO>mList = new ArrayList<>();
            for (Integer requestId:list){
                UserRequest request = requestMapper.getUserRequestDetailByRequestId(requestId);//获取到该请求的详细信息
                logger.info("获取到该订单信息:"+request.toString());
                StringBuilder s = new StringBuilder();
                if (request.getAccept()==1&&request.getComplete()==0){
                    s.append("正在进行中...");
                }else if (request.getAccept()==1&&request.getComplete()==1){
                    s.append("已完成");
                }
                DriverInfo driverInfo = userMapper.getDriverInfo(userMapper.getCustomerIdByRequestId(requestId));
                OrderItemVO vo = new OrderItemVO(
                        requestId,request.getPicurl(),
                        request.getPlace(),request.getDestination(),
                        request.getTime(),s.toString(),request.getDescription(),driverInfo.getDriverName(),driverInfo.getDriverPhone());
                mList.add(vo);
            }
            userAllOrderVO.setList(mList);
            userAllOrderVO.setCount(count);
            userAllOrderVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
            userAllOrderVO.setMsg("刷新成功");
            logger.info("完成用户接单检索:"+userAllOrderVO.toString());
            return userAllOrderVO;
        }else {
            userAllOrderVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            userAllOrderVO.setMsg("未检索到新数据");
            return userAllOrderVO;
        }

    }
    /**
     * 用户投诉反馈
     * */
    @Transactional
    public BaseResultVO addUserReport(String userPhone,String content){
        BaseResultVO baseResultVO = new BaseResultVO();
        Integer i = reportMapper.addUserReport(new UserReport(content,userPhone));
        if (i!=null){
            baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
            baseResultVO.setMsg("已收到您的投诉,我们将会尽快处理。");
            return baseResultVO;
        }else {
            baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            baseResultVO.setMsg("暂时无法使用此服务。");
            return baseResultVO;
        }

    }
    /**
     * 车主完成订单
     * */
    @Transactional
    public BaseResultVO driverCompleteOrder(String userPhone,String center,int requestId){
        BaseResultVO baseResultVO = new BaseResultVO();
        if (requestMapper.getCompleteInOrderByRequestId(requestId)!=0){
            //请求已完成
            baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            baseResultVO.setMsg("您的积分已下发。");
            return baseResultVO;
        }
        AroundSearchResData aroundSearchResData = GDUtil.AroundSearch(userPhone,center,"500",GDInfo.GD_MAP_TABLE_ID_STOP);//误差控制radius
        logger.info("范围内检索数据为:"+aroundSearchResData.toString());
        NetGDId netGDId = requestMapper.getGDId(requestId);
        logger.info(netGDId.toString());
        if(aroundSearchResData.status==1&&aroundSearchResData.info.equals("OK")&&aroundSearchResData.getDatas().size()!=0){
            for(AroundSearchInfoResData data:aroundSearchResData.getDatas()){
                //比较数据id字段，若相同则证明车主已在目的地100米范围内，可认为到达目的地
                if (data.get_id().equals(String.valueOf(netGDId.getStopId()))){
                    requestMapper.updateUserComplete(requestId);//更新用户complete标志位为1
                    baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
                    baseResultVO.setMsg("捎带请求已完成，等待发布人审核。");
                    return baseResultVO;
                }
            }
        }
            baseResultVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            baseResultVO.setMsg("请到达目的地后再点击完成。");
            return baseResultVO;

    }
    /**
     * 车主增加积分
     * */
    @Transactional
    public UserVO addDriverPoints(int requestId){
        UserVO userVO = new UserVO();
        if (requestMapper.getCompleteInOrderByRequestId(requestId)!=0){
            userVO.setMsg("请勿重复确认。");
            userVO.setResultCode(BaseResultVO.RESULT_CODE_FAIL);
            return userVO;
        }
        int driverId = requestMapper.getDriverIdByRequestId(requestId);
        int point = userMapper.getUserPointByUserId(requestMapper.getDriverIdByRequestId(requestId))+5;
        userMapper.updateDriverPoint(point,driverId);//每次完成请求可加5分
        requestMapper.updateDriverComplete(requestId);//更新车主complete标志位为1
        userVO.setMsg("车主积分+5。");
        userVO.setResultCode(BaseResultVO.RESULT_CODE_OK);
        return userVO;
    }
    /**
     * 用户查看是否请求被接受，发出通知
     * */
    @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
    public BaseResultVO getNotifyFlag(String userPhone){
        boolean flag = false;//是否更新了通知标志位
        int userId = userMapper.getUserIdByUserPhone(userPhone);
        List<NotifyInfo>list = requestMapper.getNotifyFlagByUserId(userId);
        for (NotifyInfo i:list){
            if (i.getNotifyFlag()==0&&i.getAccept()==1){//发现有新的通知
                requestMapper.updateNotifyFlag(i.getRequestId());//更新通知标志位为1
                flag = true;
            }
        }
        if(flag){
            return new BaseResultVO(null,BaseResultVO.RESULT_CODE_OK,null);
        }else {
            return new BaseResultVO(null,BaseResultVO.RESULT_CODE_FAIL,null);
        }
    }
}
